package org.example.ding.controller;

import jakarta.validation.Valid;
import org.example.ding.dto.UserRegistrationDto;
import org.example.ding.dto.UserProfileDto;
import org.example.ding.entity.User;
import org.example.ding.service.CustomUserDetailsService;
import org.example.ding.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 显示注册页面
     */
    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("userRegistration", new UserRegistrationDto());
        return "auth/register";
    }

    /**
     * 处理用户注册
     */
    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("userRegistration") UserRegistrationDto registrationDto,
                              BindingResult result,
                              RedirectAttributes redirectAttributes) {
        
        if (result.hasErrors()) {
            return "auth/register";
        }

        try {
            User user = userService.registerUser(registrationDto);
            redirectAttributes.addFlashAttribute("successMessage", 
                "注册成功！欢迎 " + user.getRealName() + "，请登录开始您的营养管理之旅。");
            return "redirect:/login";
        } catch (RuntimeException e) {
            result.rejectValue("username", "error.userRegistration", e.getMessage());
            return "auth/register";
        }
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String showLoginForm(@RequestParam(value = "error", required = false) String error,
                               @RequestParam(value = "logout", required = false) String logout,
                               Model model) {
        
        if (error != null) {
            model.addAttribute("errorMessage", "用户名或密码错误");
        }
        
        if (logout != null) {
            model.addAttribute("successMessage", "您已成功退出登录");
        }
        
        return "auth/login";
    }

    /**
     * 显示用户个人资料页面
     */
    @GetMapping("/profile")
    public String showProfile(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                             Model model) {

        User user = userService.findById(principal.getId())
            .orElseThrow(() -> new RuntimeException("用户不存在"));

        UserProfileDto profileDto = UserProfileDto.fromUser(user);
        model.addAttribute("userProfile", profileDto);
        model.addAttribute("user", user);  // 添加user对象以防模板需要

        return "user/profile-simple";
    }

    /**
     * 更新用户个人资料
     */
    @PostMapping("/profile")
    public String updateProfile(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                               @Valid @ModelAttribute("userProfile") UserProfileDto profileDto,
                               BindingResult result,
                               RedirectAttributes redirectAttributes) {
        
        if (result.hasErrors()) {
            return "user/profile-simple";
        }

        try {
            userService.updateUserProfile(principal.getId(), profileDto);
            redirectAttributes.addFlashAttribute("successMessage", "个人资料更新成功！");
            return "redirect:/profile";
        } catch (RuntimeException e) {
            result.rejectValue("email", "error.userProfile", e.getMessage());
            return "user/profile-simple";
        }
    }

    /**
     * 显示营养目标设置页面
     */
    @GetMapping("/nutrition-goals")
    public String showNutritionGoals(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                                    Model model) {
        
        User user = userService.findById(principal.getId())
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        model.addAttribute("user", user);
        model.addAttribute("bmi", user.calculateBMI());
        model.addAttribute("bmr", user.calculateBMR());
        model.addAttribute("tdee", user.calculateTDEE());
        
        return "user/nutrition-goals";
    }

    /**
     * 更新营养目标
     */
    @PostMapping("/nutrition-goals")
    public String updateNutritionGoals(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                                      @RequestParam BigDecimal calories,
                                      @RequestParam BigDecimal protein,
                                      @RequestParam BigDecimal carbs,
                                      @RequestParam BigDecimal fat,
                                      RedirectAttributes redirectAttributes) {
        
        try {
            userService.updateNutritionGoals(principal.getId(), calories, protein, carbs, fat);
            redirectAttributes.addFlashAttribute("successMessage", "营养目标更新成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        
        return "redirect:/nutrition-goals";
    }

    /**
     * 自动计算营养目标
     */
    @PostMapping("/nutrition-goals/auto-calculate")
    public String autoCalculateNutritionGoals(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                                             RedirectAttributes redirectAttributes) {
        
        try {
            userService.recalculateNutritionGoals(principal.getId());
            redirectAttributes.addFlashAttribute("successMessage", "营养目标已根据您的身体数据自动计算并更新！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        
        return "redirect:/nutrition-goals";
    }

    /**
     * 检查用户名是否可用 (AJAX)
     */
    @GetMapping("/api/users/check-username")
    @ResponseBody
    public ResponseEntity<Map<String, Boolean>> checkUsername(@RequestParam String username) {
        boolean available = userService.isUsernameAvailable(username);
        Map<String, Boolean> response = new HashMap<>();
        response.put("available", available);
        return ResponseEntity.ok(response);
    }

    /**
     * 检查邮箱是否可用 (AJAX)
     */
    @GetMapping("/api/users/check-email")
    @ResponseBody
    public ResponseEntity<Map<String, Boolean>> checkEmail(@RequestParam String email) {
        boolean available = userService.isEmailAvailable(email);
        Map<String, Boolean> response = new HashMap<>();
        response.put("available", available);
        return ResponseEntity.ok(response);
    }
}
